package com.ruoyi.system.controller;

import com.github.pagehelper.PageHelper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.OrderLetter;
import com.ruoyi.system.domain.RxOrderFollow;
import com.ruoyi.system.mapper.OrderLetterMapper;
import com.ruoyi.system.mapper.RxOrderFollowMapper;
import com.ruoyi.system.service.IOrderLetterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.PermitAll;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * 订单站内信Controller
 *
 * @author hjf
 * @date 2025-08-04
 */
@RestController
@RequestMapping("/hmk/orderLetter")
public class OrderLetterController extends BaseController {
    @Autowired
    private IOrderLetterService orderLetterService;

    @Autowired
    private RxOrderFollowMapper oFM;

    @Autowired
    private OrderLetterMapper oLM;

    @PermitAll
    @PostMapping("/getOrderMessageNumber")
    public AjaxResult getOrderMessageNumber(@RequestBody OrderLetter orderLetter) {
        if (null == orderLetter.getAuditUser()) {
            orderLetter.setAuditUser(SecurityUtils.getUserId());
        }
        List<OrderLetter> list = oLM.selectOrderLetterList3(orderLetter);
        HashMap<String, Integer> map = new HashMap();
        if (list.size() > 0) {
            map.put("orderMessageNumber", list.size());
            return success(map);
        } else {
            return success();
        }
    }

    @PermitAll
    @PostMapping("/getReplyMessageByAlready")
    public AjaxResult getReplyMessageByAlready(@RequestBody OrderLetter orderLetter) {
        orderLetter.setIssuerUser(SecurityUtils.getUserId());
        List<OrderLetter> list = oLM.getReplyMessageByAlready(orderLetter);
        if (list.size() > 0) {
            return success(list.get(0));
        } else {
            return success();
        }
    }


    @PermitAll
    @PostMapping("/updateOrderLetterReplyStatus")
    public AjaxResult updateOrderLetterReplyStatus(@RequestBody OrderLetter orderLetter) {
        orderLetter.setReplyStatus(2);
        return AjaxResult.success(oLM.updateOrderLetter(orderLetter));
    }


    /**
     * 查询订单站内信列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:list')")
    @GetMapping("/list")
    public TableDataInfo list(OrderLetter orderLetter) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401);
        }
        orderLetter.setAuditUser(currentUser.getUserId());
        orderLetter.setIssuerUser(currentUser.getUserId());
        startPage();
        PageHelper.orderBy("is_agree desc");
        List<OrderLetter> list = orderLetterService.selectOrderLetterList(orderLetter);
        return getDataTable(list);
    }

    /**
     * 导出订单站内信列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:export')")
    //@Log(title = "订单站内信", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OrderLetter orderLetter) {
        List<OrderLetter> list = orderLetterService.selectOrderLetterList(orderLetter);
        ExcelUtil<OrderLetter> util = new ExcelUtil<OrderLetter>(OrderLetter.class);
        util.exportExcel(response, list, "订单站内信数据");
    }

    /**
     * 获取订单站内信详细信息
     */
    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(orderLetterService.selectOrderLetterById(id));
    }

    /**
     * 新增订单站内信
     */
    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:add')")
    //@Log(title = "订单站内信", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OrderLetter orderLetter) {
        return toAjax(orderLetterService.insertOrderLetter(orderLetter));
    }

    /**
     * 修改订单站内信
     */
//    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:edit')")
    //@Log(title = "订单站内信", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OrderLetter orderLetter) {
        orderLetter.setReplyTime(new Date());
        orderLetter.setReplyStatus(1);
        OrderLetter oldOrderLetter = orderLetterService.selectOrderLetterById(orderLetter.getId());
        RxOrderFollow rxOrderFollow = new RxOrderFollow();
        rxOrderFollow.setId(oldOrderLetter.getOrderFollowId());
        rxOrderFollow.setReplyStatus(2);
        if (oldOrderLetter.getGoAudit() == 1L && orderLetter.getIsAgree() == 1L) {
            rxOrderFollow.setReplyContent("同意," + orderLetter.getReplyContent());
        } else if (oldOrderLetter.getGoAudit() == 1L && orderLetter.getIsAgree() == 2L) {
            rxOrderFollow.setReplyContent("不同意," + orderLetter.getReplyContent());
        } else {
            rxOrderFollow.setReplyContent(orderLetter.getReplyContent());
        }
        rxOrderFollow.setReplyTime(System.currentTimeMillis() / 1000);
        oFM.updateRxOrderFollow(rxOrderFollow);
        return toAjax(orderLetterService.updateOrderLetter(orderLetter));
    }

    /**
     * 删除订单站内信
     */
    @PreAuthorize("@ss.hasPermi('hmk:orderLetter:remove')")
    //@Log(title = "订单站内信", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(orderLetterService.deleteOrderLetterByIds(ids));
    }
}
